//支付码

//refresh：支付条码刷新方式，true 主动刷新，false自动刷新
//const URL = 'ws://172.16.20.112:8080/websocket.do';
Page({
  data: {
    timer: "", //支付码定时
    secondTimer: "", //断网后60秒后才跳转到失败页面
    urlAddress: getApp().globalData.imageUrl,
    failImg: false, //隐藏断网刷新 页面
    codeFlag: true, //显示支付码页面
    reconnectFlag: false, //长连接重新连接
    reconnectTimer: "", //长连接重连 定时器
    reconnectNumber: 0, //重新连接次数
    flag: false, //断网后是否倒计时
    number: 0, //刷新支付码事件类型，0：有网时点击更改支付码，1：断网60秒内点击跳转到支付失败页面 2：断网点击刷新按钮更改支付码
    sign: true
  },
  onLoad: function(options) {
    console.log("进入支付码页面-membershipPayment");
  },
  onShow() {
    //请求支付码 ，建立长连接
    if (this.data.codeFlag) {
      //每次进页面都要新的支付码
      this.clickPaymentCode();
      this.webSocketInit();
    }
  },
  onHide() {
    //关闭支付码请求和长连接
    if (this.data.flag) {
      this.closeSocket();
    }
  },
  onUnload() {
    //关闭支付码请求和长连接
    if (this.data.flag) {
      this.closeSocket();
    }
  },
  //手动刷新支付码
  clickPaymentCode() {
    //清除原有定时器，重新计数
    clearTimeout(this.data.timer);
    clearInterval(this.data.secondTimer);
    if (this.data.number == 0 || this.data.number == 2) {
      this.getRequest(true);
    } else {
      this.setData({
        failImg: true,
        codeFlag: false,
        flag: false
      });
    }
  },
  //自动刷新支付码
  getPaymentCode() {
    let $this = this;
    //定时器，每5秒去请求一次，有新的支付条码时，更改页面条码
    // this.data.timer = setInterval(() => {
    //   $this.getRequest(false);
    // }, 5000);
    this.data.timer = setTimeout(() => {
      $this.getRequest(false);
      this.getPaymentCode();
    }, 5000);
  },
  getRequest(refresh) {
    let $this = this;
    //请求的参数
    let parameter = {
      url: getApp().globalData.baseUrl + "/applet/pay/getPaymentCode.do",
      data: {
        refresh: refresh
      }
    };
    getApp()
      .getRequest(parameter)
      .then(res => {
        this.setData({
          number: 0,
          flag: true,
          failImg: false,
          codeFlag: true,
          sign: true
        });
        if (res.data.obj.paymentImage) {
          //接口返回的支付条码，与现有的不同时，更新条码
          if (res.data.obj.paymentImage != $this.data.userImageBase64) {
            this.setData({
              userImageBase64: res.data.obj.paymentImage,
              //拆分支付码的数字，1111 1111 1111 111111
              paymentCode1: res.data.obj.paymentCode.substring(0, 4),
              paymentCode2: res.data.obj.paymentCode.substring(4, 8),
              paymentCode3: res.data.obj.paymentCode.substring(8, 12),
              paymentCode4: res.data.obj.paymentCode.substring(12)
            });
          }
        }
        //手动刷新后，变自动刷新
        if (refresh) {
          this.getPaymentCode(false);
        }
      })
      //请求失败
      .catch(err => {
        console.log(err);
        //清除请求支付码定时器
        clearTimeout(this.data.timer);
        this.closeSocket();
        this.setData({
          sign: false
        });
        if (this.data.flag) {
          this.setData({
            number: 1
          });
          this.data.secondTimer = setTimeout(() => {
            console.log("断网后1分钟");
            clearTimeout(this.data.secondTimer);
            //隐藏扫码页面，显示断网 刷新页面
            this.setData({
              failImg: true,
              codeFlag: false,
              flag: false
            });
          }, 1000 * 60);
        } else {
          //隐藏扫码页面，显示断网 刷新页面
          this.setData({
            failImg: true,
            codeFlag: false,
            number: 2
          });
        }
      });
  },
  // 创建Socket
  webSocketInit() {
    var url = getApp().globalData.socketUrl;
    url = decodeURIComponent(url);
    let self = this;
    wx.connectSocket({
      url: url,
      header: {
        "content-type": "application/json",
        Cookie: getApp().globalData.header.Cookie,
        Authorization: null
      },
      success(res) {
        console.log("连接成功", res);
        self.initSocketCallback();
      },
      fail(res) {
        console.log("连接失败", res);
        //重新连接
        this.reconnect();
      }
    });
  },
  initSocketCallback() {
    let $this = this;
    wx.onSocketOpen(res => {
      console.log("监听 WebSocket 连接打开事件。", res);
      wx.sendSocketMessage({
        data: "ping",
        success(res) {
          console.log("第一次发送心跳。ping", res);
        },
        fail(err) {
          console.log("发送失败", err);
        }
      });
      $this.setData({
        flag: true
      });
    });
    wx.onSocketError(onError => {
      console.log("监听 WebSocket 错误。错误信息", onError);
      if (this.data.sign) {
        this.reconnect();
      }
    });
    wx.onSocketMessage(onMessage => {
      console.log(
        "监听WebSocket接受到服务器的消息事件。服务器返回的消息",
        onMessage.data
      );
      let onMessageData = onMessage.data;
      if (onMessageData == "") {
        //没有数据重新连接
        this.reconnect();
      } else {
        //正常通信 ，重新请求计数清0
        $this.setData({
          reconnectNumber: 0
        });
        //返回支付金额 跳转
        if (onMessageData != "pong") {
          wx.redirectTo({
            url: "../paymentCodeSuccess/paymentCodeSuccess?number=" + onMessageData
          });
        }
        $this.heartCheck.reset().start();
      }
    });
    wx.onSocketClose(res => {
      console.log("服务端断开  WebSocket 已关闭！", res);
      if (this.data.sign) {
        this.reconnect();
      }
    });
  },
  //重新连接事件
  reconnect(){
    if (this.reconnectFlag) return;
    this.reconnectFlag = true;
    if (this.data.reconnectNumber <= 5) {
      clearTimeout(this.data.reconnectTimer);
      this.data.reconnectTimer = setTimeout(() => {
        this.webSocketInit();
        this.reconnectFlag = false;
      }, 5000);
    }
    this.setData({
      reconnectNumber: this.data.reconnectNumber + 1
    });
  },
  // 声明心跳对象
  heartCheck: {
    timeout: 10 * 1000, // 心跳频率
    timeoutObj: null, // 向服务器发送消息定时器
    reset: function() {
      clearTimeout(this.timeoutObj);
      return this;
    },
    start: function() {
      this.timeoutObj = setTimeout(() => {
        wx.sendSocketMessage({
          data: "ping",
          success(res) {
            console.log("定时发送心跳。ping", res);
          },
          fail(err) {
            console.log("定时发送失败", err);
          }
        });
      }, this.timeout);
    }
  },
  //退出页面，关闭长连接，和支付码定时器
  closeSocket() {
    //停止发心跳
    this.heartCheck.reset();
    console.log("离开支付码页面---关闭心跳");
    //停止请求支付码
    clearTimeout(this.data.timer);
    clearInterval(this.data.secondTimer);
    console.log("清除支付码定时器------" + this.data.timer);
    //关闭长连接
    wx.closeSocket();
    wx.onSocketClose(res => {
      console.log("离开页面WebSocket 已关闭！", res);
    });
  },
  //手动刷新
  handRefresh() {
    this.setData({
      number: 2
    });
    console.log(this.data.sign);
    this.clickPaymentCode();
    this.webSocketInit();
    clearInterval(this.data.secondTimer);
    return;
  }
});